import React, { useState } from 'react'
import { 
  Card, 
  Row, 
  Col, 
  Form, 
  Input, 
  Button, 
  Avatar, 
  Typography, 
  Space, 
  Divider,
  Tag,
  Modal,
  notification,
  Alert,
  Descriptions,
} from 'antd'
import { 
  UserOutlined, 
  MailOutlined, 
  EditOutlined,
  LockOutlined,
  SaveOutlined,
  CameraOutlined,
} from '@ant-design/icons'
import { useQuery, useMutation, useQueryClient } from 'react-query'
import { authApi, authUtils } from '../services/auth'

const { Title, Text } = Typography

const UserProfile: React.FC = () => {
  const [profileForm] = Form.useForm()
  const [passwordForm] = Form.useForm()
  const [isEditingProfile, setIsEditingProfile] = useState(false)
  const [passwordModalVisible, setPasswordModalVisible] = useState(false)
  const queryClient = useQueryClient()

  // 获取当前用户信息
  const { data: currentUser, isLoading: userLoading } = useQuery(
    'currentUser',
    authApi.getCurrentUser,
    {
      onSuccess: (data) => {
        authUtils.saveUser(data)
        profileForm.setFieldsValue(data)
      },
    }
  )

  // 更新用户信息mutation
  const updateProfileMutation = useMutation(authApi.updateProfile, {
    onSuccess: (data) => {
      notification.success({
        message: '更新成功',
        description: '个人信息已更新',
      })
      authUtils.saveUser(data)
      setIsEditingProfile(false)
      queryClient.invalidateQueries('currentUser')
    },
    onError: (error: any) => {
      notification.error({
        message: '更新失败',
        description: error.message || '更新个人信息失败',
      })
    },
  })

  // 修改密码mutation
  const changePasswordMutation = useMutation(authApi.changePassword, {
    onSuccess: () => {
      notification.success({
        message: '密码修改成功',
        description: '请使用新密码登录',
      })
      setPasswordModalVisible(false)
      passwordForm.resetFields()
    },
    onError: (error: any) => {
      notification.error({
        message: '密码修改失败',
        description: error.message || '密码修改失败',
      })
    },
  })

  // 处理个人信息更新
  const handleProfileUpdate = async (values: any) => {
    await updateProfileMutation.mutateAsync(values)
  }

  // 处理密码修改
  const handlePasswordChange = async (values: any) => {
    await changePasswordMutation.mutateAsync({
      current_password: values.currentPassword,
      new_password: values.newPassword,
    })
  }

  // 获取用户角色标签颜色
  const getRoleColor = (role: string) => {
    switch (role) {
      case 'admin': return 'red'
      case 'operator': return 'blue'
      case 'viewer': return 'green'
      default: return 'default'
    }
  }

  // 获取用户角色显示名称
  const getRoleDisplayName = (role: string) => {
    switch (role) {
      case 'admin': return '管理员'
      case 'operator': return '操作员'
      case 'viewer': return '查看者'
      default: return role
    }
  }

  if (userLoading) {
    return (
      <div style={{ padding: '24px' }}>
        <Card loading />
      </div>
    )
  }

  return (
    <div style={{ padding: '24px' }}>
      <Title level={2} style={{ marginBottom: '24px' }}>
        <UserOutlined style={{ marginRight: '8px' }} />
        个人资料
      </Title>

      <Row gutter={[24, 24]}>
        {/* 基本信息卡片 */}
        <Col xs={24} lg={8}>
          <Card title="基本信息" style={{ height: '100%' }}>
            <div style={{ textAlign: 'center', marginBottom: '24px' }}>
              <Avatar 
                size={100} 
                icon={<UserOutlined />}
                style={{ backgroundColor: '#1890ff', marginBottom: '16px' }}
              />
              <Button 
                type="link" 
                icon={<CameraOutlined />}
                disabled
              >
                更换头像
              </Button>
            </div>

            <Descriptions column={1} size="small">
              <Descriptions.Item label="用户名">
                <Text strong>{currentUser?.username}</Text>
              </Descriptions.Item>
              <Descriptions.Item label="角色">
                <Tag color={getRoleColor(currentUser?.role || '')}>
                  {getRoleDisplayName(currentUser?.role || '')}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="状态">
                <Tag color={currentUser?.is_active ? 'green' : 'red'}>
                  {currentUser?.is_active ? '激活' : '禁用'}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="注册时间">
                {currentUser?.created_at ? new Date(currentUser.created_at).toLocaleDateString() : '-'}
              </Descriptions.Item>
            </Descriptions>

            <Divider />

            <Space direction="vertical" style={{ width: '100%' }}>
              <Button 
                type="primary" 
                icon={<EditOutlined />}
                onClick={() => setIsEditingProfile(true)}
                block
              >
                编辑资料
              </Button>
              <Button 
                icon={<LockOutlined />}
                onClick={() => setPasswordModalVisible(true)}
                block
              >
                修改密码
              </Button>
            </Space>
          </Card>
        </Col>

        {/* 详细信息卡片 */}
        <Col xs={24} lg={16}>
          <Card 
            title="详细信息" 
            extra={
              isEditingProfile ? (
                <Space>
                  <Button onClick={() => setIsEditingProfile(false)}>
                    取消
                  </Button>
                  <Button 
                    type="primary" 
                    icon={<SaveOutlined />}
                    onClick={() => profileForm.submit()}
                    loading={updateProfileMutation.isLoading}
                  >
                    保存
                  </Button>
                </Space>
              ) : (
                <Button 
                  type="link" 
                  icon={<EditOutlined />}
                  onClick={() => setIsEditingProfile(true)}
                >
                  编辑
                </Button>
              )
            }
          >
            {updateProfileMutation.error && (
              <Alert
                message="更新失败"
                description={(updateProfileMutation.error as any)?.message}
                type="error"
                style={{ marginBottom: '16px' }}
                showIcon
              />
            )}

            <Form
              form={profileForm}
              layout="vertical"
              onFinish={handleProfileUpdate}
              disabled={!isEditingProfile}
            >
              <Row gutter={16}>
                <Col span={12}>
                  <Form.Item
                    name="username"
                    label="用户名"
                    rules={[
                      { required: true, message: '用户名不能为空' },
                      { min: 3, message: '用户名至少3个字符' },
                    ]}
                  >
                    <Input 
                      prefix={<UserOutlined />}
                      disabled={true} // 用户名通常不允许修改
                    />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    name="email"
                    label="邮箱地址"
                    rules={[
                      { required: true, message: '邮箱不能为空' },
                      { type: 'email', message: '请输入有效的邮箱地址' },
                    ]}
                  >
                    <Input 
                      prefix={<MailOutlined />}
                      placeholder="输入邮箱地址"
                    />
                  </Form.Item>
                </Col>
              </Row>

              <Form.Item
                name="full_name"
                label="姓名"
                rules={[
                  { max: 50, message: '姓名最多50个字符' },
                ]}
              >
                <Input 
                  prefix={<UserOutlined />}
                  placeholder="输入真实姓名"
                />
              </Form.Item>
            </Form>
          </Card>

          {/* 账户统计卡片 */}
          <Card title="账户统计" style={{ marginTop: '24px' }}>
            <Row gutter={16}>
              <Col span={8}>
                <div style={{ textAlign: 'center' }}>
                  <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#1890ff' }}>
                    {authUtils.hasRole('admin') ? '所有权限' : '受限权限'}
                  </div>
                  <div style={{ color: '#666' }}>访问权限</div>
                </div>
              </Col>
              <Col span={8}>
                <div style={{ textAlign: 'center' }}>
                  <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#52c41a' }}>
                    在线
                  </div>
                  <div style={{ color: '#666' }}>当前状态</div>
                </div>
              </Col>
              <Col span={8}>
                <div style={{ textAlign: 'center' }}>
                  <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#722ed1' }}>
                    {new Date().toLocaleDateString()}
                  </div>
                  <div style={{ color: '#666' }}>最后登录</div>
                </div>
              </Col>
            </Row>
          </Card>
        </Col>
      </Row>

      {/* 修改密码Modal */}
      <Modal
        title="修改密码"
        open={passwordModalVisible}
        onCancel={() => {
          setPasswordModalVisible(false)
          passwordForm.resetFields()
        }}
        footer={null}
        width={400}
      >
        {changePasswordMutation.error && (
          <Alert
            message="密码修改失败"
            description={(changePasswordMutation.error as any)?.message}
            type="error"
            style={{ marginBottom: '16px' }}
            showIcon
          />
        )}

        <Form
          form={passwordForm}
          layout="vertical"
          onFinish={handlePasswordChange}
        >
          <Form.Item
            name="currentPassword"
            label="当前密码"
            rules={[
              { required: true, message: '请输入当前密码' },
            ]}
          >
            <Input.Password 
              prefix={<LockOutlined />}
              placeholder="输入当前密码"
            />
          </Form.Item>

          <Form.Item
            name="newPassword"
            label="新密码"
            rules={[
              { required: true, message: '请输入新密码' },
              { min: 6, message: '密码至少6个字符' },
            ]}
          >
            <Input.Password 
              prefix={<LockOutlined />}
              placeholder="输入新密码"
            />
          </Form.Item>

          <Form.Item
            name="confirmPassword"
            label="确认新密码"
            dependencies={['newPassword']}
            rules={[
              { required: true, message: '请确认新密码' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('newPassword') === value) {
                    return Promise.resolve()
                  }
                  return Promise.reject(new Error('两次输入的密码不一致'))
                },
              }),
            ]}
          >
            <Input.Password 
              prefix={<LockOutlined />}
              placeholder="再次输入新密码"
            />
          </Form.Item>

          <Form.Item style={{ marginBottom: 0, textAlign: 'right' }}>
            <Space>
              <Button onClick={() => setPasswordModalVisible(false)}>
                取消
              </Button>
              <Button 
                type="primary" 
                htmlType="submit"
                loading={changePasswordMutation.isLoading}
              >
                确认修改
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default UserProfile